/*
 * @Author: None
 * @LastEditors: None
 * @Date: 2021-11-17 11:53:43
 * @LastEditTime: 2021-11-18 11:38:46
 */
const http = require('http');

function request(option, fun) {
  var req;
  // url,data,callback,type
  var obj = option || {
    type: 'GET',
  }
  if (typeof obj == 'string') {
    obj = { url: obj, type: 'GET' };
  }
  if (obj.data && typeof obj.data == 'object') {
    // form表单提交时使用这个
    // const params = new URLSearchParams(obj.data);
    // obj.data = params.toString();
    obj.data = JSON.stringify(obj.data)
  }
  obj.callback = obj.callback || fun || new Function;
  const agent = new http.Agent({
    keepAlive: true,
  });
  var options = {
    hostname: '10.0.0.5',
    port: 10001,
    path: '/api/rest/' + obj.url,
    method: obj.type || 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-hasura-admin-secret': '9090990',
    }
  };
  var callback = function (res) {
    // console.log('STATUS: ' + res.statusCode);  
    // console.log('HEADERS: ' + JSON.stringify(res.headers));  
    // 定义了一个post变量，用于暂存请求体的信息
    var body = "";
    res.setEncoding('utf8');
    // 通过res的data事件监听函数，每当接受到请求体的数据，就累加到post变量中
    res.on('data', function (chunk) {
      // console.log('BODY: ' + chunk);
      body += chunk;
    });
    // 在res的end事件触发后，通过JSON.parse将post解析为真正的POST请求格式，然后调用传递过来的回调函数处理数据
    res.on('end', function () {
      // console.log("body = "+body);
      var json = JSON.parse(body);
      obj.callback(json);
    });
  }
  if (obj.type.toLowerCase() == 'get') {
    req = http.get(options, callback);
  } else {
    options.headers['Content-Length'] = Buffer.byteLength(obj.data);
    req = http.request(options, callback);
    req.write(obj.data);
  }
  req.on('error', function (e) {
    console.log(e.message);
  });
  req.end();
}

function format(d = new Date(), fmt = "yyyy-MM-dd HH:mm:ss") {
  d = new Date(d);
  let o = {
    "M+": d.getMonth() + 1,
    "d+": d.getDate(),
    "h+": d.getHours() % 12 == 0 ? 12 : d.getHours() % 12,
    "H+": d.getHours(),
    "m+": d.getMinutes(),
    "s+": d.getSeconds(),
    "q+": Math.floor((d.getMonth() + 3) / 3),
    S: d.getMilliseconds(),
  };
  let week = ["日", "一", "二", "三", "四", "五", "六"];
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (d.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  if (/(E+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length > 1 ? (RegExp.$1.length > 2 ? "星期" : "周") : "") +
      week[d.getDay()]);
  }
  for (let k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1
        ? o[k]
        : ("00" + o[k]).substr(("" + o[k]).length));
    }
  }
  return fmt;
}


module.exports = {
  request,format
}